package cn.whitecao.contentcenter.rocketmq;

import cn.whitecao.contentcenter.dao.RocketmqTransactionLogMapper;
import cn.whitecao.contentcenter.domain.dto.content.ShareAuditDTO;
import cn.whitecao.contentcenter.entity.RocketmqTransactionLog;
import cn.whitecao.contentcenter.service.ShareService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

/**
 * @author ：腼腆的老黄.
 * @date ：Created in 2019-10-12 19:35
 */
@RocketMQTransactionListener(txProducerGroup = "tx-add-bonus-group")
@RequiredArgsConstructor
@Slf4j
public class AddBonusTransactionListener implements RocketMQLocalTransactionListener {


    private final  ShareService shareService;
    private final RocketmqTransactionLogMapper rocketmqTransactionLogMapper;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
       log.info("rocketmq 执行事务");

        String transactionId = (String) message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        Integer shareId = Integer.valueOf((String) message.getHeaders().get("share_id"));
        try {
            this.shareService.auditByIdWithRocketMqLog(shareId,(ShareAuditDTO)o,transactionId);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
     }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("rocketmq 检查");
        String transactionId = (String) message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("transaction_Id",transactionId);
        RocketmqTransactionLog one = rocketmqTransactionLogMapper.selectOne(wrapper);
        if (one == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }else {
            return RocketMQLocalTransactionState.COMMIT;
        }

    }
}
